package com.wxl.common.wiget

import android.content.Context
import android.text.TextUtils
import android.view.KeyEvent
import android.widget.AdapterView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.core.CenterPopupView
import com.wxl.common.R
import com.wxl.common.base.AbsActivity
import com.wxl.common.event.RefreshDataEvent
import com.wxl.common.life.LifecycleManager
import com.wxl.common.room.entity.LeiGuanEntity
import com.wxl.common.room.entity.LogEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.ObservableUtil
import com.wxl.common.util.StringUtils
import com.wxl.common.util.Toll
import io.reactivex.ObservableOnSubscribe
import kotlinx.android.synthetic.main.pop_batch_update.view.*

class BatchUpdateLeiGuanPop : CenterPopupView {

    private var mData: List<LeiGuanEntity>? = null
    private val mCollectorNums = ArrayList<String>()
    private val mRows = ArrayList<String>()
    private val mHole = ArrayList<String>()

    private var mLimitData = ArrayList<LeiGuanEntity>()
    private var mSortData = ArrayList<LeiGuanEntity>()
    private var mCurrentDelay = 0L
    private var mCurrentRow = 0//当前排数
    private var mCurrentPosition = 0
    private var mCurrentHole = 0
    private var count = 0
    private var isUpdateing = false
    private var updateDialog: BasePopupView? = null

    constructor(context: Context) : super(context)

    override fun getImplLayoutId(): Int {
        return R.layout.pop_batch_update
    }

    override fun onCreate() {
        super.onCreate()

        isUpdateing = false

        val delayArr = context.resources.getStringArray(R.array.delay)

        var p = 0
        mData?.forEach {
            if(TextUtils.isEmpty(it.collectorNumber)){
                if (!mCollectorNums.contains("-")) {
                    mCollectorNums.add("-")
                }
            }
            if (!mCollectorNums.contains(it.collectorNumber) && !TextUtils.isEmpty(it.collectorNumber)) {
                mCollectorNums.add(it.collectorNumber)
            }

            p++
            mRows.add(p.toString())
            mHole.add(p.toString())
        }


        batchUpdateCollectorNumText.setText(mCollectorNums.size.toString())

        if (mRows.isNotEmpty()) {
            batchUpdateRowText.show(mRows, AdapterView.OnItemClickListener { parent, view, position, id ->
                batchUpdateRowText.setText(mRows[position])
            })
        }

        if (mHole.isNotEmpty()) {
            batchUpdateRowHoleNumText.show(mHole, AdapterView.OnItemClickListener { parent, view, position, id ->
                batchUpdateRowHoleNumText.setText(mRows[position])
            })
        }

        batchUpdateStartDelayText.show(delayArr.asList(), AdapterView.OnItemClickListener { parent, view, position, id ->
            batchUpdateStartDelayText.setText(delayArr[position])
        })

        batchUpdateRowDelayText.show(delayArr.asList(), AdapterView.OnItemClickListener { parent, view, position, id ->
            batchUpdateRowDelayText.setText(delayArr[position])
        })

        batchUpdateRowHoleDelayText.show(delayArr.asList(), AdapterView.OnItemClickListener { parent, view, position, id ->
            batchUpdateRowHoleDelayText.setText(delayArr[position])
        })


        batchUpdateCancelBtn.setOnClickListener {
            if (!isUpdateing) {
                dismiss()
                LogEntity.addLog("延时方案","批量修改","取消")
            }
        }

        batchUpdateSureBtn.setOnClickListener {
            if (!isUpdateing) {
                LogEntity.addLog("延时方案","批量修改","修改")
                batchUpdate()
            }
        }
    }


    private fun batchUpdate() {
        var row = 0L
        var hole = 0L
        if (!TextUtils.isEmpty(batchUpdateRowText.text)) {
            row = batchUpdateRowText.text.toString().toLong()
        }
        if (!TextUtils.isEmpty(batchUpdateRowHoleNumText.text)) {
            hole = batchUpdateRowHoleNumText.text.toString().toLong()
        }

        if (checkUpdateRowHole(row, hole)) {
            updateDialog = XPopup.Builder(context)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .asLoading("正在修改中，请稍后...")
                .show()
            (context as AbsActivity).addPop(updateDialog as BasePopupView)
            isUpdateing = true
            if (mCollectorNums.isEmpty()) {
                mData?.let {
                    mLimitData.addAll(it)
                    updateRowHole(row, hole,
                        object : ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
                            override fun onNext(t: List<LeiGuanEntity>) {
                                updateEnd()
                            }
                        })
                }
            } else {
                updateByCollector(row, hole)
            }
        }

    }

    /**
     * 更新一个采集器里的数据
     */
    private fun updateByCollector(row: Long, hole: Long) {
        if (mCurrentPosition < mCollectorNums.size) {
            matchCollectorNumData(mCollectorNums[mCurrentPosition], object :
                ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
                override fun onNext(t: List<LeiGuanEntity>) {
                    if (t.isNotEmpty()) {
                        updateRowHole(row, hole,
                            object :
                                ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
                                override fun onNext(t: List<LeiGuanEntity>) {
                                    mCurrentPosition++
                                    updateByCollector(row, hole)
                                }
                            })
                    } else {
                        Toll.toll("没有符合采集器编号的数据。")
                    }
                }
            })
        } else {
            updateEnd()
        }
    }

    /**
     * 修改结束
     */
    private fun updateEnd() {
        isUpdateing = false
        if (mSortData.isEmpty()) {
            updateDialog?.dismiss()
            return
        }
        DBHelper.insertNewLeiGuanData(object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                val mRefreshDataEvent = RefreshDataEvent()
                mRefreshDataEvent.isRefresh = true
                LifecycleManager.manager.refreshLiveData(mRefreshDataEvent)
                updateDialog?.dismiss()
                dismiss()
            }
        }, *mSortData.toTypedArray())
    }


    /**
     * 修改排数和孔数
     */
    private fun checkUpdateRowHole(row: Long, hole: Long): Boolean {
        if (row > 0 && hole == 0L) {
            Toll.toll("请填写每排孔数")
            return false
        }
        if (row == 0L && hole > 0) {
            Toll.toll("请填写排数")
            return false
        }
        if (row < 0L || hole < 0) {
            Toll.toll("请填写正确的排数或孔数")
            return false
        }

        if (row * hole < mData!!.size) {
            Toll.toll("请填写正确的排数或孔数")
            return false
        }

        return checkDelayTotalLimit(row, hole)

    }

    /**
     *  修改排数和孔数
     */
    private fun updateRowHole(
        row: Long,
        hole: Long,
        callback: ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>
    ) {
        ObservableUtil.doNext(ObservableOnSubscribe<List<LeiGuanEntity>> {
            mLimitData.forEach {
                if (count % hole == 0L) {//分排
                    mCurrentHole = 1
                    mCurrentRow++
                    if (count == 0) {//起始
                        setStartDelay(it)
                    } else {
                        setRowData(it)
                    }
                } else {
                    mCurrentHole++
                    setHoleData(mCurrentHole, it)
                }

                mSortData.add(it)
                count++
            }
            it.onNext(mLimitData)
        }, callback)
    }


    /**
     * 设置孔
     */
    private fun setHoleData(mCurrentHole: Int, lg: LeiGuanEntity) {
        var holeDelay = 0L
        if (!TextUtils.isEmpty(batchUpdateRowHoleDelayText.text)) {
            holeDelay = batchUpdateRowHoleDelayText.text.toString().toLong()
        }
        mCurrentDelay += holeDelay
        lg.delay = (mCurrentDelay).toString()
        lg.holeNumber = StringUtils.TenToRowHole16(mCurrentRow.toString(),mCurrentHole.toString())
        lg.rowNumber = mCurrentRow.toString()
    }

    /**
     * 设置排头
     */
    private fun setRowData(lg: LeiGuanEntity) {
        var rowDelay = 0L
        if (!TextUtils.isEmpty(batchUpdateRowDelayText.text)) {
            rowDelay = batchUpdateRowDelayText.text.toString().toLong()
        }
        mCurrentDelay += rowDelay
        lg.delay = (mCurrentDelay).toString()
        lg.holeNumber = StringUtils.TenToRowHole16(mCurrentRow.toString(),"1")
        lg.rowNumber = mCurrentRow.toString()
    }

    /**
     * 检查总延时是否超过限制值
     */
    private fun checkDelayTotalLimit(row: Long, hole: Long): Boolean {
        var startDelay = 0L
        var holeDelay = 0L
        var rowDelay = 0L
        if (!TextUtils.isEmpty(batchUpdateStartDelayText.text)) {
            startDelay = batchUpdateStartDelayText.text.toString().toLong()
        }
        if (!TextUtils.isEmpty(batchUpdateRowDelayText.text)) {
            rowDelay = batchUpdateRowDelayText.text.toString().toLong()
        }
        if (!TextUtils.isEmpty(batchUpdateRowHoleDelayText.text)) {
            holeDelay = batchUpdateRowHoleDelayText.text.toString().toLong()
        }

        val totalDelay = startDelay + (row - 1) * rowDelay + (mData!!.size - row) * holeDelay
        if(totalDelay > 12000){
            Toll.toll("总延时不能超过12s")
        }
        return totalDelay <= 12000
    }

    /**
     * 设置初始延时
     */
    private fun setStartDelay(lg: LeiGuanEntity) {
        var startDelay = 0L
        if (!TextUtils.isEmpty(batchUpdateStartDelayText.text)) {
            startDelay = batchUpdateStartDelayText.text.toString().toLong()
        }
        mCurrentDelay = startDelay
        lg.rowNumber = mCurrentRow.toString()
        lg.holeNumber = StringUtils.TenToRowHole16(mCurrentRow.toString(),"1")
        lg.delay = startDelay.toString()
    }

    /**
     * 筛选符合采集器编号的数据
     */
    private fun matchCollectorNumData(
        collectorNum: String,
        callback: ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>
    ) {
        mLimitData.clear()
        ObservableUtil.doNext(ObservableOnSubscribe<List<LeiGuanEntity>> {
            mData?.forEach {
                if (TextUtils.equals(collectorNum, it.collectorNumber)) {
                    mLimitData.add(it)
                } else if(TextUtils.isEmpty(it.collectorNumber) && TextUtils.equals("-",collectorNum)){
                    mLimitData.add(it)
                }
            }
            it.onNext(mLimitData)
        }, callback)
    }


    private fun setLeiGuanData(mData: List<LeiGuanEntity>): BatchUpdateLeiGuanPop {
        this.mData = mData
        return this
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_F1 || keyCode == KeyEvent.KEYCODE_BACK) {
            batchUpdateCancelBtn.performClick()
        }
        if (keyCode == KeyEvent.KEYCODE_F4) {
            batchUpdateSureBtn.performClick()
        }
        return super.onKeyDown(keyCode, event)
    }


    companion object {
        fun show(context: Context, mData: List<LeiGuanEntity>) {
            val pop = BatchUpdateLeiGuanPop(context).setLeiGuanData(mData)
            XPopup.Builder(context)
                .dismissOnTouchOutside(false)
                .asCustom(pop)
                .show()
            (context as AbsActivity).addPop(pop as BasePopupView)
        }
    }
}